package com.tim.ying.zk.provider;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import com.tim.ying.zk.util.ZKUtils;

public class ZKServiceProvider {
	
	
	
	public void publish(Remote remote,String host,int port){
		String url = publishService(remote, host, port);
		if(url!=null){
			ZooKeeper zk = ZKUtils.createServer();
			//ZooDefs.Ids.OPEN_ACL_UNSAFE 最大权限
			ZKUtils.createNode(zk,ZKUtils.ZK_PROVIDER_PATH, url, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
		}
	}
	
	public String publishService(Remote remote,String host,int port){
		String url = null;
		try {
			url = String.format("rmi://%s:%d/%s", host,port,remote.getClass().getName());
			LocateRegistry.createRegistry(port);
			Naming.rebind(url, remote);
		} catch (RemoteException | MalformedURLException e) {
			System.out.println("发布服务的时候出错 " + e);
			e.printStackTrace();
			url = null;
		} 
		return url;
	}
}
